package com.example.goodog.activities;

/**
 * @Author Paresh N. Mayani
 * @Web http://www.technotalkative.com
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;

import com.example.goodog.GoogleImageBean;
import com.example.goodog.ImageLoader;
import com.example.goodog.R;

public class GoogleSearchAPIExampleActivity extends Activity {
	/** Called when the activity is first created. */

	private TableLayout tableLayoutImages;
	private EditText txtSearchText;	
	private ArrayList<Object> listImages;
	private Activity activity;

	String strSearch = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_photos);

		activity = this;
		tableLayoutImages = (TableLayout) findViewById(R.id.tblresults);
		txtSearchText = (EditText) findViewById(R.id.txtViewSearch);

	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
		Bundle extras = getIntent().getExtras();
		if(extras != null && (txtSearchText.getText() == null || txtSearchText.getText().toString().equals("")))
		{
			txtSearchText.setText(extras.getString("searchString", ""));
			SearchForPicturesByInputString();
	    }
	}

	public class getImagesTask extends AsyncTask<Integer, Void, Void>
	{
		ArrayList<JSONObject> jsons;
		//ProgressDialog dialog;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();

			//dialog = ProgressDialog.show(GoogleSearchAPIExampleActivity.this, "", "Please wait...");
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			/*if(dialog.isShowing())
		   {
			   dialog.dismiss();
		   }
			 */

			try {
				for (JSONObject json : jsons) {


					JSONObject responseObject = json.getJSONObject("responseData");
					JSONArray resultArray = responseObject.getJSONArray("results");

					listImages = getImageList(resultArray);

					TableRow tr;
					if(tableLayoutImages.getChildCount() == 0 || ((TableRow)tableLayoutImages.getChildAt(tableLayoutImages.getChildCount()-1)).getChildCount()==3)
					{
						tr = new TableRow(activity);
					}
					else
					{
						tr = ((TableRow)tableLayoutImages.getChildAt(tableLayoutImages.getChildCount()-1));
						tableLayoutImages.removeView(tr);
					}

					for (int i = 0; i < listImages.size(); i++)
					{

						ImageLoader imageLoader = new ImageLoader(activity.getApplicationContext());; 
						ImageView imgViewImage = new ImageView(activity);
						imgViewImage.setOnClickListener(new OnClickListener() {
							
							@Override
							public void onClick(View v) {
								Intent resultIntent = new Intent();
				        		setResult(Activity.RESULT_OK, resultIntent);
				        		Bitmap bitmap = ((BitmapDrawable)((ImageView)v).getDrawable()).getBitmap();
				        		resultIntent.putExtra("ImageBitmap", bitmap );
								activity.finish();
							}
						});
						GoogleImageBean imageBean = (GoogleImageBean) listImages.get(i);
						imgViewImage.setTag(imageBean.getThumbUrl());
						imageLoader.DisplayImage(imageBean.getThumbUrl(), activity, imgViewImage);
						tr.addView(imgViewImage);
						if(tr.getChildCount() == 3)
						{
							tableLayoutImages.addView(tr);
							tr = new TableRow(activity);
						}				   
					}

					if(tr.getChildCount() != 0)
					{
						tableLayoutImages.addView(tr);
					}

				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		@Override
		protected Void doInBackground(Integer... params) {
			int startimage = 0;
			if(startimage == 9)
			{
				startimage = 8;
			}
			for (int i = 0; i < params.length; i++) {
				{
					startimage = params[i];
					URL url;
					try {
						url = new URL("https://ajax.googleapis.com/ajax/services/search/images?" +
								"v=1.0&q="+strSearch+"&rsz=8&start="+startimage );

						URLConnection connection = url.openConnection();
						connection.addRequestProperty("Referer", "http://technotalkative.com");

						String line;
						StringBuilder builder = new StringBuilder();
						BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
						while((line = reader.readLine()) != null) {
							builder.append(line);
						}

						JSONObject json = new JSONObject(builder.toString());
						if(jsons == null)
							jsons = new ArrayList<JSONObject>();
						jsons.add(json);
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}
			return null;

		}

		public ArrayList<Object> getImageList(JSONArray resultArray)
		{
			ArrayList<Object> listImages = new ArrayList<Object>();
			GoogleImageBean bean;

			try 
			{
				for(int i=0; i<resultArray.length(); i++)
				{
					JSONObject obj;
					obj = resultArray.getJSONObject(i);
					bean = new GoogleImageBean();

					bean.setTitle(obj.getString("title"));
					bean.setThumbUrl(obj.getString("tbUrl"));

					System.out.println("Thumb URL => "+obj.getString("tbUrl"));

					listImages.add(bean);

				} 
				return listImages;
			}
			catch (JSONException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			return null;
		}

		
	}

		public void btnSearchClick(View v)
		{
			SearchForPicturesByInputString();
		}

		public void SearchForPicturesByInputString() {
			strSearch = txtSearchText.getText().toString();
			strSearch = Uri.encode(strSearch);
			tableLayoutImages.removeAllViews();
			System.out.println("Search string => "+strSearch);
			getImagesTask my_task = new getImagesTask();
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
			    my_task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 0,9,17,25);
			else
			    my_task.execute(0,9,17,25);
		}
	
}